package com.joint.web.action.app;

import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.Pager;
import com.google.common.collect.Maps;
import com.joint.base.bean.EnumManage;
import com.joint.base.entity.Users;
import com.joint.base.entity.system.Locations;
import com.joint.base.service.AdminService;
import com.joint.base.util.DataUtil;
import com.joint.base.util.StringUtils;
import com.joint.core.entity.ProAttend;
import com.joint.core.entity.ProInfo;
import com.joint.core.entity.ProSignIn;
import com.joint.core.service.ProAttendService;
import com.joint.core.service.ProInfoService;
import com.joint.core.service.ProSignInService;
import com.joint.web.action.BaseAction;
import com.opensymphony.xwork2.ModelDriven;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.struts2.convention.annotation.ParentPackage;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * 后台Action类 - 项目信息管理
 */
@ParentPackage("app")
public class ProinfoAction extends BaseAction implements ModelDriven<ProInfo> {

    private static final long serialVersionUID = -4787241461181578464L;

    private ProInfo proInfo;
	private List<ProInfo> proinfoList;
    private String latitude;
    private String longitude;
    private String addressSignin;

    @Resource
    private ProInfoService proInfoService;
    @Resource
    protected AdminService adminService;
    @Resource
    private ProSignInService proSignInService;
    @Resource
    private ProAttendService proAttendService;  //考勤设置

    /**
     * 签到
     * @return
     * @throws Exception
     */
    public String assign() throws Exception {

        users = getRequestUsers();
        company = users.getCompany();
        if(company == null)
            return ajaxHtmlAppResult(0, "未找到用户所属企业！",null);

        if(StringUtils.isEmpty(keyId)){
            return ajaxHtmlAppResult(0, "尚未选择项目！", null);
        }
        proInfo = proInfoService.get(keyId);

        //该用户当天已经进行了基础签到
        Date now = new Date();
        Date now1 = DataUtil.StringToDate(DataUtil.DateToString(now, "yyyy/MM/dd"), "yyyy/MM/dd");
        Date now2 = DataUtil.StringToDate(DataUtil.DateToString(DataUtil.getAfterDay(now, 1), "yyyy/MM/dd"), "yyyy/MM/dd");
        HashMap<String,Object> params = new HashMap<String,Object>();
        params.put("proInfo", proInfo);
        List<ProSignIn> proSigninList = (List<ProSignIn>) proSignInService.findByPagerAndCompany(new Pager(0), "modifyDate", now1, now2, users, company, params).getList();

        //根据后台设定考勤时间点的时间区间，签到时间不在正常和异常时间区间内的，提示用户：“时间未到，不能签到。”
        String stime = DataUtil.DateToString(now, "HH:mm:ss");
        now = DataUtil.StringToDate(stime, "HH:mm:ss");

        Pager pagerPA = proAttendService.findByPagerAndProInfo(new Pager(0),proInfo,new BaseEnum.StateEnum[]{BaseEnum.StateEnum.Enable});
        List<ProAttend> proAttendList = (List<ProAttend>) pagerPA.getList();

        if (proAttendList.size()==0){
            return ajaxHtmlAppResult(0, "该项目尚未设定考勤时间！", null);
        }

        boolean flag = false;
        int status = 0;
        int hasSigned;
        for(ProAttend pa:proAttendList){
            Date ars = pa.getRegularStart();
            Date are = pa.getRegularEnd();
            Date aurs = pa.getUnRegularStart();
            Date aure = pa.getUnRegularEnd();

            hasSigned = 0;
            if ( proSigninList != null ) {
                for(ProSignIn ps:proSigninList){
                    Date mdate = DataUtil.StringToDate(DataUtil.DateToString(ps.getModifyDate(), "HH:mm:ss"), "HH:mm:ss");
                    if ((DataUtil.TimeDiff(mdate, ars)>=0 && DataUtil.TimeDiff(mdate, are)<60000) || (DataUtil.TimeDiff(mdate, aurs)>=0 && DataUtil.TimeDiff(mdate, aure)<60000)) {
                        hasSigned = 1;
                        break;
                    }
                }
            }

            if (DataUtil.TimeDiff(now, ars)>=0 && DataUtil.TimeDiff(now, are)<60000) {
                if(hasSigned == 1){
                    return ajaxHtmlAppResult(0, "每个考勤区间只能进行一次签到，不能重复签到！", null);
                }
                flag = true;
                status = 1;
                break;
            }

            if (DataUtil.TimeDiff(now, aurs)>=0 && DataUtil.TimeDiff(now, aure)<60000){
                if(hasSigned == 1){
                    return ajaxHtmlAppResult(0, "每个考勤区间只能进行一次签到，不能重复签到！", null);
                }
                flag = true;
                status = 0;
                break;
            }

            if(DataUtil.TimeDiff(now, ars)<0 || (DataUtil.TimeDiff(now, are)>0 && DataUtil.TimeDiff(now, aurs)<0)){
                return ajaxHtmlAppResult(0, "时间未到，不能签到！", null);
            }

            if(DataUtil.TimeDiff(now, aure)>0){
                return ajaxHtmlAppResult(0, "已过签到时间，不能签到！", null);
            }
        }

//        if(!flag){
//            return ajaxHtmlAppResult(0, "时间未到，不能签到！", null);
//        }
        //LogUtil.info("status2 :" +status);

        ProSignIn proSignIn = new ProSignIn();
        proSignIn.setProInfo(proInfo);
        proSignIn.setName(proInfo.getName());
        proSignIn.setCreater(users);
        proSignIn.setCompany(company);
        proSignIn.setStatus(status);
        proSignIn.setAddress(addressSignin);

        Locations location=new Locations();
        location.setLatitude(new BigDecimal(latitude));
        location.setLongitude(new BigDecimal(longitude));
        location.setCoordType(EnumManage.CoordTypeEnum.bd09ll);
        location.setAddress(addressSignin);

        proSignInService.saveEntity(proSignIn,location);

        return ajaxHtmlAppResult(1, "签到成功！", null);
    }

	/**
	 * 项目信息列表
	 * @return String
	 * @throws Exception
	 */
	public String getList() throws Exception {

        pager = new Pager();
        pager.setPageNumber(pageIndex);// 页码
        pager.setPageSize(pageSize);// 页Size
        if(StringUtils.isNotEmpty(pageProperty)&& StringUtils.isNotEmpty(pageKeyword)){
            pager.setProperty(pageProperty);
            pager.setKeyword(pageKeyword);
        }
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);

        Map<String, Object> map;
        map = Maps.newHashMap();
        map.put("state", new BaseEnum.StateEnum[]{BaseEnum.StateEnum.Enable});
        if(catalog==1){
            map.put("proState", 0);
        }else{
            map.put("proState", 1);
        }
        map.put("name", pageKeyword);
        pager = proInfoService.findByPagerAndLimit(pager, usersService.getLoginInfo(), usersService.getCompanyByUser(), map);

        proinfoList = (List<ProInfo>) pager.getList();
        if(proinfoList == null){
            proinfoList = new ArrayList<ProInfo>();
        }

        List<JSONObject> dataRows = new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();

        for (ProInfo temp : proinfoList) {
            Map<String, Object> tempMap = proInfoService.getListItemMap(temp);
            dataRows.add(JSONObject.fromObject(tempMap));
        }

        data.put("pageNum", pageIndex);//页数
        data.put("pageSize", proinfoList.size());//记录数
        data.put("pageCount", pager.getPageCount());//总页数
        data.put("totalCount", pager.getTotalCount());//总记录数
        data.put("dataRows", JSONArray.fromObject(dataRows));//数据
        return ajaxHtmlAppResult(1, "", JSONObject.fromObject(data));
	}

    /**
     * 和用户相关的项目信息列表(在项目总监，项目组成员，新建人里面)
     * @return String
     * @throws Exception
     */
    public String getListRelated() throws Exception {

        pager = new Pager();
        pager.setPageNumber(pageIndex);// 页码
        pager.setPageSize(pageSize);// 页Size
        if(StringUtils.isNotEmpty(pageProperty)&& StringUtils.isNotEmpty(pageKeyword)){
            pager.setProperty(pageProperty);
            pager.setKeyword(pageKeyword);
        }
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);

        Map<String, Object> map;
        map = Maps.newHashMap();
        map.put("state", new BaseEnum.StateEnum[]{BaseEnum.StateEnum.Enable});
        map.put("proState", 0);
        map.put("name", pageKeyword);
        pager = proInfoService.findByPagerAndLimit(pager, usersService.getLoginInfo(), usersService.getCompanyByUser(), map);

        proinfoList = (List<ProInfo>) pager.getList();
        if(proinfoList == null){
            proinfoList = new ArrayList<ProInfo>();
        }

        List<JSONObject> dataRows = new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();

        //如果不是该项目的总监或项目组成员，则不允许签到、反馈、请假
        users = getRequestUsers();
        int flg;
        for (ProInfo temp : proinfoList) {
            flg = 0;
            if (users.equals(temp.getChief())){
                flg = 1;
            }else {
                Set<Users> usersSet = temp.getGroup();
                if (usersSet!=null && usersSet.size()>0) {
                    if (usersSet.contains(users)) {
                        flg = 1;
                    }
                }
            }
            if(flg==1){
                Map<String, Object> tempMap = proInfoService.getListItemMap(temp);
                dataRows.add(JSONObject.fromObject(tempMap));
            }
        }

        data.put("pageNum", pageIndex);//页数
        data.put("pageSize", proinfoList.size());//记录数
        data.put("pageCount", pager.getPageCount());//总页数
        data.put("totalCount", pager.getTotalCount());//总记录数
        data.put("dataRows", JSONArray.fromObject(dataRows));//数据
        return ajaxHtmlAppResult(1, "", JSONObject.fromObject(data));
    }

	/**
	 * 项目信息详情
     *
	 * @return String
	 * @throws Exception
	 */
	public String getDetail() throws Exception {

        if (StringUtils.isNotEmpty(keyId)) {
            proInfo = proInfoService.get(keyId);
            if (proInfo != null) {
                Map<String, Object> data = proInfoService.getDetailMap(proInfo);
                return ajaxHtmlAppResult(1, "", JSONObject.fromObject(data));
            }
        }
        return ajaxHtmlAppResult(0, "无法找到该文档，可能已被删除！", null);
	}

	@Override
	public ProInfo getModel() {
		if(proInfo == null){
            proInfo = new ProInfo();
		}
		return proInfo;
	}

    public String getLatitude() {
        return latitude;
    }

    public void setLatitude(String latitude) {
        this.latitude = latitude;
    }

    public String getLongitude() {
        return longitude;
    }

    public void setLongitude(String longitude) {
        this.longitude = longitude;
    }

    public String getAddressSignin() {
        return addressSignin;
    }

    public void setAddressSignin(String addressSignin) {
        this.addressSignin = addressSignin;
    }
}
